package com.xuanwei.schedule.handler.order;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuanwei.dao.entity.XwOrder;
import com.xuanwei.schedule.service.OrderService;
import com.xuanwei.xwcommon.consts.MqType;
import com.xuanwei.xwcommon.entity.dto.MessageDto;
import com.xuanwei.xwcommon.enums.MqHandlerType;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author jiangyong
 * @Description TODO
 * @Date 2019/7/25 15:35
 **/
@JobHandler(value = "QueryPaySuccess")
@Component
@Slf4j
public class QueryPay extends IJobHandler {

    private OrderService orderService;

    private AmqpTemplate amqpTemplate;

    public QueryPay(OrderService orderService, AmqpTemplate amqpTemplate) {
        this.orderService = orderService;
        this.amqpTemplate = amqpTemplate;
    }

    @Override
    public ReturnT<String> execute(String s) throws Exception {
        int index = 1;
        int pageSize = 10;
        while (true) {
            Page<XwOrder> page = new Page<>(index, pageSize);
            List<OrderService.NoPayStatus> ids = orderService.findNoPayStatus(page);
            if (ids != null && ids.size() > 0) {
                ids.forEach(i -> {
                    MessageDto<Integer> messageDto = new MessageDto<>();
                    if (i.getType() == 1) {
                        messageDto.setType(MqHandlerType.ORDER_PAY_SUCCESS);
                    }
                    if (i.getType() == 2) {
                        messageDto.setType(MqHandlerType.ORDER_NO_PAY);
                    }
                    messageDto.setData(i.getOrderId());
                    amqpTemplate.convertAndSend(MqType.ORDER, JSON.toJSONString(messageDto));
                });
                index++;
            } else {
                break;
            }
        }
        return SUCCESS;
    }
}
